#ifndef SANGAME_BASE_SINGLETON_H_
#define SANGAME_BASE_SINGLETON_H_

#include "base/lock.h"

namespace sangame {
namespace base {

template<class T>
class Singleton {
public:
    class Clearer {
    public:
        ~Clearer() {
            if(Singleton::Instance()) {
                delete Singleton::Instance();
            }
        }
    };

    static T* Instance() {
        if(NULL == _instance) {
            Lock lock(_m);
            if(NULL == _instance) {
                static Clearer clr;
                _instance = new T();
            }
        }
        return _instance;
    }

private:
    static Lock::Mutex _m;
    static T* _instance;
};

template<class T>
T* Singleton<T>::_instance = NULL;

template<class T>
Lock::Mutex Singleton<T>::_m;

}
}

#endif // SANGAME_BASE_SINGLETON_H_